import React, { Fragment } from 'react';
import { Select, Checkbox, Input } from 'antd';
import Empty from '@/tool/components/PageEmpty';
import styles from './index.less';
import { useSetState, useUpdateEffect } from 'ahooks';
const { Search } = Input;
import _ from 'lodash';
interface IProps {
  value: any;
  options: any[];
  style: object;
  selectName: string;
  selectKey: string;
  valueKey?: string;
  labelKey?: string;
  showSearch: boolean;
  onChange: (value: any) => void;
  dropdownClassName?: string;
}

function MulSelect(props: IProps) {
  const {
    onChange,
    value,
    options,
    selectName,
    selectKey,
    showSearch,
    valueKey = 'value',
    labelKey = 'label',
  } = props;

  const [state, setState] = useSetState({
    searchText: '',
    isArrList: true,
    value: props.value,
    options: props.options,
  });

  const emptyStyle = _.isEmpty(options) ? styles.emptyStyle : '';

  useUpdateEffect(() => {
    if (!_.isEqual(state.options, props.options)) {
      setState({ searchText: '' });
    }
  }, [options]);

  let all = value;
  if (options.length && (value.length === options.length || value === 'all')) {
    all = [selectName];
  }
  const onSearch = (value: string) => {
    setState({ searchText: value });
  };

  const treeCheckOptions = {};
  const filterArray = showSearch
    ? options.filter((n) => n[labelKey].includes(state.searchText))
    : options;

  const filterCheckArray = filterArray.filter((n) => value.includes(n[valueKey]));
  if (filterCheckArray.length > 0 && filterCheckArray.length != filterArray.length) {
    treeCheckOptions.indeterminate = true;
  }
  const treeCheck = filterCheckArray.length > 0 && filterCheckArray.length == filterArray.length;

  const _onDropdownVisibleChange = (visible: boolean) => {
    if (visible && state.searchText) {
      setState({ searchText: '' });
    }
  };

  useUpdateEffect(() => {
    if (state.searchText) {
      filterArray.length > 0 && onChange && onChange(filterArray.map((n) => n[valueKey]));
    }
  }, [state.searchText]);

  return (
    <Select
      key={selectKey}
      mode="multiple"
      maxTagCount={2}
      dropdownClassName={`${styles.dropdown} ${emptyStyle} ${props.dropdownClassName}`}
      // suffixIcon={<CaretDownOutlined />}
      dropdownRender={() => {
        return (
          <section data-dropdown-render={selectKey}>
            {(options.length && (
              <Fragment>
                {showSearch && (
                  <Search
                    value={state.searchText}
                    onSearch={onSearch}
                    onChange={(e) => {
                      setState({ searchText: e.target.value });
                    }}
                    style={{ marginTop: '10px' }}
                  />
                )}
                {filterArray.length ? (
                  <Fragment>
                    <Checkbox
                      indeterminate={
                        showSearch
                          ? treeCheckOptions.indeterminate
                          : value.length !== 0 && value.length !== options.length
                      }
                      onChange={() => {
                        if (showSearch) {
                          const valueRe = _.cloneDeep(value);
                          if (treeCheck) {
                            _.pullAll(
                              valueRe,
                              filterCheckArray.map((n) => n[valueKey]),
                            );
                            onChange(valueRe);
                          } else {
                            const fvalue = [...valueRe, ...filterArray.map((n) => n[valueKey])];
                            onChange(_.uniq(fvalue));
                          }
                        } else {
                          onChange(
                            value.length !== options.length
                              ? options.map((item) => item.value)
                              : [],
                          );
                        }
                      }}
                      checked={showSearch ? treeCheck : value.length === options.length}
                    >
                      全选
                    </Checkbox>
                    <Checkbox.Group
                      value={showSearch ? filterCheckArray.map((i) => i[valueKey]) : value}
                      onChange={(val) => {
                        if (showSearch) {
                          const cloneData = _.cloneDeep(value);
                          const pullValue = filterCheckArray.filter(
                            (n) => !val.includes(n[valueKey]),
                          );
                          if (pullValue.length > 0) {
                            _.pullAll(
                              cloneData,
                              pullValue.map((n) => n[valueKey]),
                            );
                            onChange(cloneData);
                          } else {
                            const fValue = _.uniq([...cloneData, ...val]);
                            onChange(fValue);
                          }
                        } else {
                          onChange(val);
                        }
                      }}
                    >
                      {filterArray.map((c) => {
                        return (
                          <Checkbox value={c.value} key={c.value}>
                            <div className={styles.label}>{c.label}</div>
                          </Checkbox>
                        );
                      })}
                    </Checkbox.Group>
                  </Fragment>
                ) : (
                  <Empty />
                )}
              </Fragment>
            )) || <Empty />}
          </section>
        );
      }}
      showArrow
      {..._.omit(props, [
        'onChange',
        'selectName',
        'selectKey',
        'labelKey',
        'valueKey',
        'showSearch',
      ])}
      showSearch={false}
      value={all}
      data-all={value.length === options.length}
      onDropdownVisibleChange={(open: boolean) => _onDropdownVisibleChange(open)}
      // tagRender={tagRender}
    />
  );
}

export default MulSelect;
